package cn.nju.sirx.programmingpearls2nd.chapter01;

import java.io.PrintStream;
import java.util.Random;

import cn.nju.sirx.datastructure.collection.BitSet;

/**
 * Generate a bit set with given given length and size (elements count).
 * 
 * @author SirX
 */
public class BitSetGenerator {

    public BitSetGenerator(int length, int size) {
        if (length <= 0 || size < 0 || length < size) {
            throw new IllegalArgumentException();
        }
        this.length = length;
        this.size = size;
    }

    public BitSet generate() {
        return generate(System.out);
    }

    public BitSet generate(PrintStream printStream) {
        BitSet bitSet = new BitSet(length);
        Random random = new Random();
        for (int i = 0; i < size; i++) {
            int offsetInSet = random.nextInt(length);
            while (bitSet.test(offsetInSet)) {
                offsetInSet = (offsetInSet + 1) % length;
            }
            bitSet.set(offsetInSet);
            if (printStream != null) {
                printStream.println(offsetInSet);
            }
        }
        return bitSet;
    }

    private int length;
    private int size;

}
